package com.chaowen.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

import android.os.Handler;
import android.os.Message;

import com.chaowen.config.Config;
import com.chaowen.model.UserInfo;
import com.chaowen.util.SocketCreate;

public class AnswerTask extends Task{
	private Handler handler;
	private String studentid;//学生学号
	private int exercisesId;//题目编号
	private String answer;//答案选择
	private int answerState;//答题状态

	@Override
	public void onPostExecute(int result) {
		Message msg = handler.obtainMessage();
		switch (result) {
		case 33:
			msg.what = 33;
			handler.sendMessage(msg);
			break;
		case 31:
			msg.what = 31;
			handler.sendMessage(msg);
			UserInfo.answer = "";
			Config.startNumbers++;
			break;
		case 30:
			msg.what = 30;
			handler.sendMessage(msg);
			UserInfo.answer = "";
			Config.startNumbers++;
			break;
		case -1:
			msg.what = -1;
			handler.sendMessage(msg);
			break;
		case 4:
			msg.what = 4;
			handler.sendMessage(msg);
			break;
		case 32:
			msg.what = 32;
			handler.sendMessage(msg);
			break;
		}
	}
	
	@Override
	public void execute() {
		studentid = UserInfo.userName;
		exercisesId = Config.startNumbers;
		answer = UserInfo.answer;
		if(answer==null||answer.equals("")) {
			onPostExecute(33);
			return;
		}
		Thread t = new Thread(AnswerTask.this);
		t.start();
	}
	
	@Override
	public void run() {
		Socket socket = null;
		try {
			socket = SocketCreate.createSocket();
			BufferedReader reader = SocketCreate.getReader(socket);
			PrintWriter writer = SocketCreate.getWriter(socket);
			System.out.println("发送给服务器的：" + exercisesId+"    "+studentid +"     "+answer);
			writer.println("answer," +exercisesId+","+ studentid +","+answer);
			String get = reader.readLine();
			System.out.println("get---->" + get);
			answerState = Integer.parseInt(get);
			System.out.println("答题" + answerState);
			onPostExecute(answerState);
			System.out.println("socketstate: " + socket.isClosed());
		} catch (Exception e) {
			try {
				if (socket != null)
					socket.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			onPostExecute(4);
			e.printStackTrace();
		}
	}

	@Override
	public void setHandler(Handler handler) {
		this.handler = handler;
	}

}
